#pragma once 
#include <iostream>
#include <unistd.h>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"

using namespace std;
const string defaultfile = "./dict.txt";
const string sep = ": ";

class Dict
{
private:
    // 下载文件
    bool Load()
    {
        // 打开文件
        fstream in(_filename);
        if(in.is_open())
        {
            LOG(FATAL, "open %s fail", _filename.c_str());
            return false;
        }
        // 
        string line;
        while(getline(in, line))
        {
            if(line.empty()) continue; // 为空行
            auto pos = line.find(sep); // 找sep
            if(pos == string::npos) continue; // 没找到
            string word = line.substr(0, pos); // 截取单词
            if(word.empty()) continue; 
            string han = line.substr(pos+sep.size()); // 截取翻译
            if(word.empty()) continue; 
            LOG(DEBUG, "load sucess, word: %s, han: %s", word.c_str(), han.c_str());

            _dict.insert(word, han);
        }
        // 关闭文件
        in.close();
        LOG(DEBUG, "open %s success", _filename.c_str());
        return true;
    }
public:
    Dict(const string filename = defaultfile):_filename(filename)
    {

    }

    string Translate(const string &word)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            return "未找到";
        }
        return iter->second;
    }

    ~Dict()
    {}
private:
    unordered_map<string, string> _dict;
    string _filename;
};